package ui

import scala.swing._
import swing.event._
import java.awt.Color
import javax.swing._
import core.ScalaCheckers

object SimpleGUI extends SimpleGUIApplication {
	def top = mainFrame
	val game = ScalaCheckers
	val board = new Array[Array[ToggleButton]](game.STD_BOARD_SIZE)
	var iBoard = new Array[Array[Int]](game.STD_BOARD_SIZE)
	var selectedButton = false
	var x1,x2,y1,y2 = 0
	var lightIcon = createImageIcon("red.gif", "light")
	var darkIcon = createImageIcon("black.gif", "dark")
	var lightKingIcon = createImageIcon("redKing.gif", "lightKing")
	var darkKingIcon = createImageIcon("blackKing.gif", "darkKing")
	var RGBColor = new Color(200,0,0)
		
	val mainFrame = new MainFrame {
		title = "Scala Checkers"
		preferredSize = new Dimension (600,640)
		initializeBoard()
		contents = new BoxPanel(Orientation.Vertical){
			contents += turnBar
			contents += ui
			contents += messageBar
		}
		
		// Listener for button presses
		for (y <- 0 until game.STD_BOARD_SIZE){
			for( x <- 0 until game.STD_BOARD_SIZE){
				listenTo(board(x)(y))
			    val activeButton = board(x)(y)	
			}
		}			
		
		reactions += {
			case ButtonClicked(activeButton) => 
			/* Need to check if is first half of move and is a spot contained by current player
			 * if so, then highlight the box and await second half of move.
			 * After second half of move, run normal move verification.
			 */
			
			
			if (selectedButton == false){
				val nameParser = "([0-7])([,])([0-8])".r
					val s = activeButton.name
					s match {
						case nameParser (cx,comma,cy) =>{
							x1 = cx.toInt
							y1 = cy.toInt
							if(game.debug)
								println("Piece chosen at " + x1 + "," + y1)
						}
						case _ =>{
							if (game.debug)
								println("name parse error")
						}
					}
				if(game.isEmpty(x1+1,y1+1)
					|| (game.isLight(x1+1,y1+1)	&& game.isDarkPlayerTurn())
					|| (game.isDark(x1+1,y1+1) && game.isLightPlayerTurn())){
						messageBar.text = "Invalid Piece Selection"
						activeButton.selected = false
					}
				else {
					if (game.debug)
						println("You selected valid square " + activeButton.name)
					
					messageBar.text = "Choose your destination for move validation"
					selectedButton = true
				}
			}
			else {
				val nameParser = "([0-7])([,])([0-8])".r
				val s = activeButton.name
				s match {
					case nameParser (cx,comma,cy) =>{
						x2 = cx.toInt
						y2 = cy.toInt
						if (game.debug){
							println("x1 = " + x1 + ", y1 = " + y1)
							println("Destination chosen at " + x2 + "," + y2)
						}
						if (game.makeMove(x1+1,y1+1,x2+1,y2+1)){
							if(game.debug)
								println ("valid move!")
							messageBar.text = "Valid Move! From " + (x1+1) + "," + (y1+1) + " to " + 
																	(x2+1) + "," + (y2+1)
						}
						else {
							if(game.debug)
								println ("invalid move!")
							messageBar.text = "Invalid Move!"
						}
					}
					case _ =>{
							if(game.debug)
								println("name parse error")
					}
					
				}
				selectedButton = false
				updateBoard
			}
		}		
	}

	lazy val ui = new GridPanel(8,8) {
		for (y <- 0 until game.STD_BOARD_SIZE){
			for( x <- 0 until game.STD_BOARD_SIZE){
				contents += board(x)(y)
			}
		}			
	}
	
	lazy val messageBar = new Label{text = "Welcome to Scala Checkers!"}
	lazy val turnBar = new Label{
		if (game.isDarkPlayerTurn)
			text = "Dark Player's Turn"
			else
				text = "Light Player's Turn"
	}
	
	
def initializeBoard(){
	game.init
	for (i <- 0 until game.STD_BOARD_SIZE) {
				board(i) = new Array[ToggleButton](game.STD_BOARD_SIZE);
			}
	for (y <- 0 until game.STD_BOARD_SIZE){
			for( x <- 0 until game.STD_BOARD_SIZE){
				board(x)(y) = new ToggleButton
				board(x)(y).foreground = Color.WHITE
				board(x)(y).name = x.toString() + "," + y.toString()
				if (x % 2 == y % 2) {
					board(x)(y).background = Color.BLACK
				}
					else{
					board(x)(y).background = RGBColor
					board(x)(y).enabled = false// White spaces
					}
			}// end for x
		}//end for y 
	updateBoard
	} // end initializeBoard

def updateBoard{
	iBoard = game.getBoardState
	for (y <- 0 until game.STD_BOARD_SIZE){
			for( x <- 0 until game.STD_BOARD_SIZE){
				//Place dark pieces
				if (iBoard(x)(y) == game.DARK){
					board(x)(y).icon = darkIcon
				}
				if (iBoard(x)(y) == game.DARK_KING){
					board(x)(y).icon = darkKingIcon
				}
				//Place light pieces
				if (iBoard(x)(y) == game.LIGHT){
					board(x)(y).icon = lightIcon
				}
				if (iBoard(x)(y) == game.LIGHT_KING){
					board(x)(y).icon = lightKingIcon
				}
				//Empty other spots
				if (iBoard(x)(y) == game.EMPTY){
					board(x)(y).icon = null
				}
				//De-select boxes
				if (board(x)(y).selected){
					board(x)(y).selected = false
				}
			}
	}
	if (game.isDarkPlayerTurn)
			turnBar.text = "Dark Player's Turn"
				else
					turnBar.text = "Light Player's Turn"
						
	if (game.debug == true)
		game.printBoard
		
	if (game.gameHasBeenWon == 1){
		messageBar.text = "Congratulations Dark Player!"
		turnBar.text = "Game Over!"
		for (y <- 0 until game.STD_BOARD_SIZE){
			for( x <- 0 until game.STD_BOARD_SIZE){
				board(x)(y).enabled = false
			}
		}
	}
	if (game.gameHasBeenWon == 2){
		messageBar.text = "Congratulations Light Player!"
		turnBar.text = "Game Over!"
		for (y <- 0 until game.STD_BOARD_SIZE){
			for( x <- 0 until game.STD_BOARD_SIZE){
				board(x)(y).enabled = false
			}
		}
	}
}

/** Returns an ImageIcon, or null if the path was invalid. */
def createImageIcon (path:String, description: String): ImageIcon = {
    val imgURL = getClass.getResource(path)
    if (imgURL != null) {
        return new ImageIcon(imgURL, description)
    } else {
        println("Couldn't find file: " + path)
        return null;
    }
}



}